<template>
<div class="container" v-loading="containerLoading">
  <el-form class="form-container" :model="userInfoData" label-width="auto" style="max-width: 600px;font-weight: bold" size="large" >
    <el-form-item label="用户姓名" >
      <el-input v-model="userInfoData.userName"/>
    </el-form-item>
    <el-form-item label="用户性别">
        <el-radio-group v-model="userInfoData.sex">
        <el-radio :value="0">男生</el-radio>
        <el-radio :value="1">女生</el-radio>
        </el-radio-group>
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="userInfoData.email" placeholder="暂未绑定邮箱"/>
    </el-form-item>
    <el-form-item label="注册时间">
      <el-col >
        <el-date-picker
            v-model="userInfoData.createTime"
            placeholder="time"
            disabled
        /> -
        <el-time-picker
            v-model="userInfoData.createTime"
            arrow-control
            disabled
            placeholder="time"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="是否为管理员">
      <el-switch
          disabled
          v-model="isAdmin"
          size="large"
      />
    </el-form-item>
    <el-form-item label="用户头像">
      <el-upload
                 ref="uploadAvatarFile"
                 accept="JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                 list-type="picture-card"
                 :auto-upload="false"
                 :limit="1"
                 v-model:file-list="fileList"
                 :on-change="loadJsonFromFile"
      >
        <el-icon><Plus /></el-icon>

        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
          </div>
        </template>
      </el-upload>

      <el-dialog class="user-avatar-preview" v-model="dialogVisible">
        <el-image style="width: 500px; height: 500px" :src="dialogImageUrl" fit="cover" />
<!--        <img w-full :src="dialogImageUrl" alt="Preview Image" />-->
      </el-dialog>

<!--      <el-image class="user-avatar" :src="userInfoData.userAvatar" fit="contain" @click="uploadUserAvatar()" />-->
    </el-form-item>
    <el-form-item label="签到积分">
      {{userInfoData.integral}}
    </el-form-item>
    <el-form-item label="个人简介">
      <el-input v-model="userInfoData.userProfile" type="textarea" />
    </el-form-item>
    <el-form-item style="margin-left: 100px">
      <el-button type="primary" @click="confirmUpdateUser()">确认更新</el-button>
<!--      <el-button>Cancel</el-button>-->
    </el-form-item>
  </el-form>
</div>
</template>

<script setup>
import {onMounted, ref, reactive, watch} from "vue";
import {useRouter,useRoute} from "vue-router";
import myAxios from "../../../plugins/myAxios.js";
import {ElMessage} from "element-plus";
import {Delete, Download, Plus, ZoomIn} from "@element-plus/icons-vue";
import axios from "axios";


const router = useRouter();
const route = useRoute();
const isAdmin = ref(false);

const routerUserId = ref(null);
const containerLoading = ref(false); //当前页面全屏loading

const userInfoData = reactive({
  id:0,
  userName: '', //姓名
  sex: '', //性别
  createTime: '', //注册时间
  userRole: '',  //是否为管理员
  userAvatar: false, //用户头像
  integral: 0, //签到积分
  userProfile: '', //个人简介
  email:''
})

const uploadAvatarFile = ref([]); //头像文件

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref([]);

const loadJsonFromFile = (file, fileList2) =>{
  console.log(file)
  console.log(fileList2)
  uploadAvatarFile.value = fileList2
  console.log(uploadAvatarFile.value)
}


/**
 * 移除头像
 */
const handleRemove = () => {
  fileList.value = [];
}


/**
 * 头像预览
 * @param file
 */
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

/**
 * 监听是否是管理员变量
 */
watch( () => userInfoData.userRole,val => {
      isAdmin.value = val === 1;
    },
    { deep: true , immediate: true }
)


onMounted(() =>{
  routerUserId.value = null;
  routerUserId.value = history.state.userId;
  containerLoading.value = true;
  queryUserInfo();
})

/**
 * 更新用户信息
 */
const confirmUpdateUser = async () => {
  // todo loading效果
  // 解析上传的文件
  console.log("更新");
  console.log(uploadAvatarFile.value);
  console.log(uploadAvatarFile);
  console.log(fileList.value);
  containerLoading.value = true;

  //更新用户头像
    if(fileList.value.length > 0 && fileList.value[0].name != null && fileList.value[0].raw !== undefined){
      let fileInfo = fileList.value[0].raw;
      console.log("fileInfo");
      console.log(fileInfo);
      const maxFileSize = 1024 * 1024 * 5 //最大5MB
      if(fileInfo.size > maxFileSize){
        ElMessage.error("文件大小不能超过5MB，请重新上传文件");
        return;
      }
      let formData = new FormData();
      formData.append('file',fileInfo);
      formData.append('id',userInfoData.id)
      const instance = axios.create({
        withCredentials: true // 允许携带cookie
      });
      await instance.post('http://localhost:8101/api/user/update/avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 设置请求头，指定为multipart/form-data
        }
      }).then(res => {
        console.log(res);
        res = res.data;
        if(res.code === 0 || res.message === 'ok') {
          console.log(res)
          //更新用户具体信息
          new Promise(() => {
            updateUserInfo();
          }).then(() => {
            ElMessage.success("更新成功");
          })
        }else{
          ElMessage.error("更新失败");
        }
      }).catch(() => {
        ElMessage.error("更新失败");
        containerLoading.value = false;
      })
    }else{
      new Promise(() => {
        updateUserInfo();
      })
    }
  containerLoading.value = false;
}

/**
 * 更新用户信息
 * @returns {Promise<void>}
 */
const updateUserInfo = async () =>{
  const res = await myAxios.post('/user/update',{
    id:userInfoData.id,
    userName:userInfoData.userName,
    sex:userInfoData.sex,
    userProfile:userInfoData.userProfile,
    email:userInfoData.email
  });
  if(res.code === 0){
    ElMessage.success("更新成功");
  }else{
    ElMessage.error(res.message);
  }
  containerLoading.value = false;
  location.reload();
}

/**
 * 查询用户信息
 */
const queryUserInfo = async () => {
  // if(userId !== undefined && userId != null){
  //   console.log(userId)
  // }
  const res = await myAxios.post('/user/get',{
    id:routerUserId.value
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: '服务器内部错误',
    })
  });
  if(res.code === 0){
    let user = res.data;
    userInfoData.userName = user.userName;
    userInfoData.sex = user.sex;
    userInfoData.createTime = user.createTime;
    userInfoData.userRole = user.userRole;
    userInfoData.userAvatar = user.userAvatar;
    dialogImageUrl.value = user.userAvatar;
    fileList.value[0]  = {
          name: 'default.jpeg',
          url: user.userAvatar
    }
    userInfoData.integral = user.integral;
    userInfoData.userProfile = user.userProfile;
    userInfoData.id = user.id;
    userInfoData.email = user.email
  }else{
    ElMessage.error(res.message);
  }
  containerLoading.value = false;
}
</script>

<style scoped lang="less">
.container{
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-image: url("../../../assets/img/appearance/userInfo.jpg");
  background-repeat: no-repeat;
  background-position: center right;
  background-size: cover;
  .form-container{
    //margin: 0 auto;
    margin:30px 0 0 30px;
  }
}


.font-color{
  color: #ef0606;
}

.user-avatar{
  width: 180px;
  height: 180px;
  cursor:default;
}



// 头像上传区
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
  margin: 20px 0 0 20px;
}
</style>